package first.web;


import first.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

/**
 * 项目名称：File
 * 类 名 称：${NAME}
 * 类 描 述：TODO
 * 创建时间：2019-12-01 22:17
 * 创 建 人：jacksonmike
 */
@WebServlet(name = "ServletUpload", value = "/upload")
@MultipartConfig(maxFileSize = 1024*1024*10, maxRequestSize = 1024*1024*100)
public class ServletUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //1获取request中表单的部分(Part 表单中一部分内容
        Collection<Part> parts = request.getParts();
        String basePath=this.getServletContext().getRealPath("/WEB-INF/upload");
        // System.out.println(basePath);
        File dir=new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();//创建文件夹
        }
        if(parts!=null){
            for (Part part : parts) {
                //判断是文件项，还是普通项
                String submittedFileName = part.getSubmittedFileName();
                if(submittedFileName==null){//普通表单元素
                    //获取用户名
                    String name = part.getName();
                    String value = request.getParameter(name);
                    System.out.println(name+":"+value);
                }else{ // 表单文件项  没有选择文件 文件名称是 ""

                    //重新获取名称，submittedFileName有问题（IE ,fireFox）form-data; name="file1"; filename="2.jpeg"
                    String dis= part.getHeader("Content-Disposition");
                    String realFileName=dis.substring(dis.lastIndexOf("filename=")+10,dis.length()-1);
                    realFileName=realFileName.substring(realFileName.lastIndexOf("\\")+1);
                    if(submittedFileName==""){
                        continue;//继续处理下一个
                    }
                    //有文件保存

                    //控制文件的后缀


                    String newFileName = UploadUtils.createNewFileName(realFileName);
                    String newPath = UploadUtils.createNewPath(basePath, realFileName);


                    part.write(newPath+"/"+newFileName);
                    //缓存文件
                    part.delete();//
                    //响应内容
                    out.write("<h3>上传成功:</h3>"+realFileName+"<br/>");
                }
            }
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
